<?php
namespace app\admin\controller;
use app\common\model\AdminUser as AdminUserModel;
use app\common\model\Department as DepartmentModel;

use app\common\controller\AdminBase;
use think\Db;

/**
 * 后台部门
 * Class Department
 * @package app\admin\controller
 */
class Department extends AdminBase
{
    protected $admin_user_model;
    protected $department_model;

    protected function _initialize()
    {
        parent::_initialize();
        $this->admin_user_model = new AdminUserModel();
        $this->department_model = new DepartmentModel();

        $department_list       = $this->department_model->order(['sort' => 'DESC', 'id' => 'DESC'])->select();
        $this->assign('department_list', $department_list);
    }

    /**
     * 后台部门
     * @return mixed
     */
    public function index()
    {
        return $this->fetch();
    }

    /**
     * 添加部门
     * @param string $pid
     * @return mixed
     */
    public function add()
    {
        return $this->fetch();
    }

    /**
     * 保存部门
     */
    public function save()
    {
        if ($this->request->isPost()) {
            $data            = $this->request->post();
            $validate_result = $this->validate($data, 'Department');

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                if ($this->department_model->save($data)) {
                    $this->success('保存成功');
                } else {
                    $this->error('保存失败');
                }
            }
        }
    }

    /**
     * 编辑部门
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {
        $department = $this->department_model->find($id);

        return $this->fetch('edit', ['department' => $department]);
    }

    /**
     * 更新部门
     * @param $id
     */
    public function update($id)
    {
        if ($this->request->isPost()) {
            $data            = $this->request->post();
            $validate_result = $this->validate($data, 'Department');

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                if ($this->department_model->save($data, $id) !== false) {
                    $this->success('更新成功');
                } else {
                    $this->error('更新失败');
                }
            }
        }
    }

    /**
     * 删除部门
     * @param $id
     */
    public function delete($id)
    {
        $admin_user = $this->admin_user_model->where(['did' => $id])->find();
        if (!empty($admin_user)) {
            $this->error('此部门下存在用户，不可删除');
        }
        if ($this->department_model->destroy($id)) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
}